package org.example.cloudapply.controller;


import jakarta.validation.constraints.Pattern;

import org.example.cloudapply.entity.Admin;
import org.example.cloudapply.entity.Result;
import org.example.cloudapply.service.AdminService;
import org.example.cloudapply.utils.JwtUtil;
import org.example.cloudapply.utils.Md5Util;
import org.example.cloudapply.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Validated
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //用户注册
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$")String username, @Pattern(regexp = "^\\S{5,16}$") String password){
        System.out.println("aaa");
        Admin u=adminService.findByUserName(username);
        if(u==null){
            System.out.println("aaa");
            adminService.register(username,password);
            return  Result.success();
        }
        else {
            return Result.error("用户名已被占用");
        }
    }
    //用户登录
    @PostMapping("/login")
    public Result login( @Pattern(regexp = "^\\S{5,16}$")String username,
                         @Pattern(regexp = "^\\S{5,16}$") String password){
        Admin loginUser=adminService.findByUserName(username);
        if(loginUser==null){
            return Result.error("用户名错误");
        }
        if(Md5Util.getMD5String(password).equals(loginUser.getPasswordHash())){
            Map<String ,Object> claims=new HashMap<>();
            System.out.println("aaaaaaaaaaaaa");
            claims.put("id",loginUser.getAdminId());
            claims.put("username",loginUser.getUsername());
            String token= JwtUtil.genToken(claims);
            //将token存在redis中
            ValueOperations<String,String> ops=stringRedisTemplate.opsForValue();
            ops.set(token,token,12, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }
    //用户详细详细
    @RequestMapping("/userInfo")
    public Result<Admin> userInfo(){
        Map<String,Object> map= ThreadLocalUtil.get();
        String username=(String)map.get("username");
        Admin admin=adminService.findByUserName(username);
        return Result.success(admin);
    }

}